<template>
  <a-modal :title="calcTitle" :visible="visible" width="1000px" @cancel="visible = false">
    <a-steps :current="current" size="small" v-if="operatorType === 'add' || operatorType === 'edit'">
      <a-step title="基础规则">1</a-step>
      <a-step title="其他规则" />
      <a-step title="确认创建" />
    </a-steps>
    <template v-if="current === 0 || current === 2">
      <entity-view ref="firstStepForm" :operatorType="operatorType" :model="beanInfo" form-item-width="100%"
                   :labelCol="{span:4}" :wrapperCol="{span:8}" :rules="firstStepRules">
        <form-item label="收银员返现活动名称" prop="mcName" v-model="beanInfo.mcName" :disabled="disabled"></form-item>
        <form-item label="机构名称" prop="orgInfo">
          <a-tree-select
            :dropdownStyle="{maxHeight: '50vh'}"
            treeDataSimpleMode
            v-model="beanInfo.orgInfo"
            style="width: 100%"
            :tree-data="treeData"
            tree-checkable
            placeholder="请选择参与机构"
            :disabled="disabled"
            :showCheckedStrategy="SHOW_PARENT"
            :getPopupContainer="() => $refs.treeContainer"
            @change="setOrgInfo"
          />
          <div ref="treeContainer" style="position: relative;max-height: 300px;">

          </div>
        </form-item>
        <a-form-model-item label="活动时间" prop="mcDateRange" :autoLink="false" ref="mcDateRange" :style="'width: 100%'" class="form-item">
          <a-row>
            <a-col :span="20">
              <a-range-picker v-model="beanInfo.mcDateRange" allow-clear :disabled="disabled" @change="() => {$refs.mcDateRange.onFieldChange()}" :disabledDate="current => disabledDate({current})"></a-range-picker>
            </a-col>
            <a-col :span="4" v-if="current !== 2">
              <a href="javascript:" @click="setLongTime()" v-if="operatorType === 'add' || operatorType === 'edit'" style="margin-left: 10px">长期</a>
            </a-col>
          </a-row>
        </a-form-model-item>
        <a-form-model-item label="预计活动资金" :autoLink="false" prop="budget" ref="budget" :style="'width: 100%'" class="form-item">
          <a-radio-group name="discountTransferMode" v-model="beanInfo.discountTransferMode" :disabled="disabled" :options="[{label: '返现', value: '0'}]"></a-radio-group>
          <a-input-number :min="0" placeholder="请输入返现金额" v-model="beanInfo.budget" :max-length="9"
                          :disabled="disabled" @blur="() => {$refs.budget.onFieldBlur()}"></a-input-number>
          <span> 元</span>
        </a-form-model-item>
        <a-form-model-item label="活动商户" :wrapperCol="{span:18}" prop="merchantInfo" :auto-link="false" style="width: 100%">
          <!-- 由于在不选择商户时，所属机构商户数据量可能过大，会导致前端卡死。所以暂时修改商户信息为必填。此处提示暂时注释 -->
          <!-- <div style="color: red;">当前如果未选择任何商户或商圈，默认所选机构所有有效商户的收银员达标后享受返现优惠活动</div> !-->
          <div class="child-item">
            <merchant-selector
              ref="merchantSelector"
              v-model="beanInfo.merchantInfo"
              :checked-org-info="checkedOrgInfo"
              :disabled="disabled"
              @uploaded="templateUploaded"
              :hasUploaded="beanInfo.hasUploaded"></merchant-selector>
          </div>
          <div class="child-item">
            <a-row>
              <a-col :span="12" v-if="current !== 2">
                <a-form-model-item label="商圈号" :wrapperCol="{span:24}" labelAlign="left" prop="merchantCircleInfo">
                  <a-row type="flex" justify="space-between" align="bottom">
                    <a-col :span="19">
                      <a-textarea placeholder="请输入商圈编号" v-model="beanInfo.merchantCircleRows"></a-textarea>
                    </a-col>
                    <a-col :span="4">
                      <a href="javascript:" @click="getBusinessArea">确定</a>
                    </a-col>
                  </a-row>
                  <div class="tip">
                    请输入商圈编号，一行一个，最多输入10个<br>
                    已录入{{ beanInfo.merchantCircleInfo.length }}个商圈
                  </div>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="商圈名称" :labelCol="{span:6}" :wrapperCol="{span:24}" labelAlign="left">
                  <a-row type="flex" justify="space-between" v-for="(i,index) in beanInfo.merchantCircleInfo" :key="i.mchntNo">
                    <a-col :span="20">{{ i.mchntName }}({{i.mchntNo}})</a-col>
                    <a-col :span="4"  v-if="current !== 2"><a href="javascript:" @click="deleteMerchantInfo('merchantCircleInfo', index)">删除</a></a-col>
                  </a-row>
                </a-form-model-item>
              </a-col>
            </a-row>
          </div>
        </a-form-model-item>
        <a-form-model-item label="纳入营销的交易" prop="upLineProduce" :wrapper-col="{span:20}"  :autoLink="false" ref="upLineProduce" :style="'width: 100%'" class="form-item">
          <div>线下</div>
          <div :style="{ borderBottom: '1px solid #E9E9E9' }">
            <a-checkbox :indeterminate="indeterminate" :checked="checkAll" @change="onCheckAllChange" :disabled="disabled">
              全选
            </a-checkbox>
          </div>
          <a-checkbox-group v-model="beanInfo.upLineProduce" @change="onCheckboxChange" :disabled="disabled">
            <div class="label">二维码（客户主扫）：</div>
            <a-space>
              <a-checkbox value="PM003000">微信扫码支付</a-checkbox>
              <a-checkbox value="PM003010">支付宝扫码支付</a-checkbox>
              <a-checkbox value="PM003020">银联云闪付扫码支付</a-checkbox>
              <a-checkbox value="PM003030">手机银行APP扫码支付</a-checkbox>
            </a-space>
            <div class="label">二维码（客户被扫）：</div>
            <a-space>
              <a-checkbox value="MC021000">微信被扫</a-checkbox>
              <a-checkbox value="MC021010">支付宝被扫</a-checkbox>
              <a-checkbox value="MC021020">银联二维码被扫</a-checkbox>
            </a-space>
          </a-checkbox-group>
        </a-form-model-item>
      </entity-view>
    </template>
    <div class="hr" v-if="current === 2"></div>
    <template v-if="current === 1 || current === 2">
      <entity-view ref="secondStepForm" :operatorType="operatorType" :model="beanInfo" :visible="visible" form-item-width="100%" :labelCol="{span:6}" :wrapperCol="{span:10}" :rules="secondStepRules">
        <form-item label="达标条件" :wrapper-col="{span:12}">
          <div style="line-height: 1.4;margin-top: 10px">
            以下为达标维度; 若不配置则默认不检查收银员以下维度;<br/>
            配置一项或多项维度且选择“<span style="color: red">或</span>”则只要满足任意一个维度可享受优惠;<br/>
            配置一项或多项维度且选择“<span style="color: red">且</span>”则需要满足所有维度才可享受优惠;
          </div>
        </form-item>
        <a-form-model-item label="有效交易定义" prop="criteriaLimit" ref="criteriaLimit" :auto-link="false"
                           :wrapper-col="{span: 10}" :style="'width: 100%'" class="form-item">
          <div class="tip" style="margin-top: 10px">针对达标条件中达标笔数，达标金额有效；</div>
          <a-row>
            <a-col :span="6">交易金额≥</a-col>
            <a-col :span="18">
              <a-input-number :min="0" placeholder="请输入金额" v-model="beanInfo.criteriaLimit" :disabled="disabled"
                              :max-length="9" @blur="() => {$refs.criteriaLimit.onFieldBlur()}"/>
              <span> 元</span>
            </a-col>
          </a-row>
        </a-form-model-item>
        <form-item label="统计周期" input-type="select" prop="statPeriod" v-model="beanInfo.statPeriod" :options="[
          {value: '0', name: '与活动起止一致'},
          {value: '1', name: '自然月度'},
          {value: '2', name: '自然季度'},
          {value: '3', name: '自然年'},
        ]" :disabled="disabled"></form-item>
        <a-form-model-item label="周期内收银员交易金额达标" prop="criteriaAmount" ref="criteriaAmount" :auto-link="false"
                           :wrapper-col="{span: 10}" :style="'width: 100%'" class="form-item">
          <a-row type="flex" justify="space-between">
            <a-col :span="16">
              <a-input-number :min="0" placeholder="请输入周期内收银员交易金额达标" v-model="beanInfo.criteriaAmount"
                       :disabled="disabled" :max-length="9" @blur="() => {$refs.criteriaAmount.onFieldBlur()}"/>
              <span> 元</span>
            </a-col>
            <a-col :span="7">
              <a-radio-group v-model="beanInfo.criteriaFlag" :options="[
                {label: '或', value: '0'},
                {label: '且', value: '1'},
              ]" :disabled="disabled"></a-radio-group>
            </a-col>
          </a-row>
        </a-form-model-item>
        <form-item label="周期内收银员交易笔数达标" prop="criteriaQuantity">
          <a-input-number :min="0" placeholder="请输入周期内收银员交易笔数达标" v-model="beanInfo.criteriaQuantity" :max-length="9" :disabled="disabled" :precision="0"/>
          <span> 笔</span>
        </form-item>
        <div class="hr" v-if="current === 2"></div>
        <a-form-model-item label="营销方式" prop="ruleInfo" ref="ruleInfo" :auto-link="false"
                           :wrapper-col="{span: 18}" :style="'width: 100%'" class="form-item">
          <a-radio-group v-model="beanInfo.cashbackMethod" :options="[
            {value: '0', label: '按交易金额比例'},
            {value: '1', label: '按交易金额固定返现'},
          ]" :disabled="disabled" @change="onCashbackChange"></a-radio-group>
          <div class="child-item" v-if="beanInfo.cashbackMethod === '0'">
            <div class="step-rule-item" v-for="(i, index) in beanInfo.ruleInfo" :key="index">
              <span>交易金额</span>
              <!-- 交易金额范围从第二阶梯开始起始值自动从第一阶梯获取，并且不让修改 -->
              <a-input-number :min="0" class="small-input" size="small" :disabled="disabled || index > 0" v-model="i.criteriaFloor"/>
              <span>至</span>
              <a-input-number :min="0" :max-length="9" class="small-input" size="small" :disabled="disabled" v-model="i.criteriaCelling"/>
              <span>元，按比例</span>
              <a-input-number class="small-input" size="small" :disabled="disabled" v-model="i.cashbackRatio" :min="0" :max="1000"/>
              <span>‰ 上限返</span>
              <a-select class="small-select" size="small" :disabled="disabled" v-model="i.discountType">
                <a-select-option value="0">现金(元）</a-select-option>
              </a-select>
              <a-input-number class="small-input" size="small" :disabled="disabled" v-model="i.discount" :min="0"/>
              <a href="javascript:" v-if="current !== 2" @click="deleteCashbackRule(index)">删除</a>
            </div>
            <a href="javascript:" @click="addStepRuleItem" v-if="current !== 2 && beanInfo.ruleInfo.length > 0">添加阶梯</a>
          </div>
          <div class="child-item" v-if="beanInfo.cashbackMethod === '1'">
            <div class="step-rule-item" v-for="(i, index) in beanInfo.ruleInfo" :key="index">
              <span>交易金额</span>
              <a-input-number :min="0" class="small-input" size="small" :disabled="disabled || index > 0" v-model="i.criteriaFloor"/>
              <span>至</span>
              <a-input-number :min="0" class="small-input" size="small" :disabled="disabled" v-model="i.criteriaCelling"/>
              <span>元，固定返</span>
              <a-select class="small-select" size="small" :disabled="disabled" v-model="i.discountType">
                <a-select-option value="0">积分(个)</a-select-option>
              </a-select>
              <a-input-number class="small-input" size="small" :disabled="disabled" v-model="i.discount" :min="0"/>
              <a href="javascript:" v-if="current !== 2 && beanInfo.ruleInfo.length > 0" @click="deleteCashbackRule(index)">删除</a>
            </div>
            <a href="javascript:" @click="addStepRuleItem" v-if="current !== 2">添加阶梯2</a>
          </div>
        </a-form-model-item>
        <form-item label="单个收银员返现退出条件" :wrapper-col="{span:12}">
          <div style="line-height: 1.4;margin-top: 10px">
            以下为单个收银员退出条件营销活动，<br>
            不配置则活动结束自然退出(可能需要补营销资金)，<br>
            <span style="color: #F1545D;">满足其中之一则收银员不再享受返现优惠！</span>
          </div>
        </form-item>
        <form-item label="单个收银员统计交易笔数上限" prop="quantityLimitPerson">
          <a-space>
            <a-input-number placeholder="请输入单个收银员统计交易笔数上限" v-model="beanInfo.quantityLimitPerson" :precision="0" :min="0" :disabled="disabled"/>
            <span>笔，或</span>
          </a-space>
        </form-item>
        <form-item label="单个收银员统计交易金额上限" prop="amountLimitPerson">
          <a-space>
            <a-input-number placeholder="请输入单个收银员统计交易金额上限" v-model="beanInfo.amountLimitPerson" :min="0" :disabled="disabled"/>
            <span>元，或</span>
          </a-space>
        </form-item>
        <form-item label="单个收银员返现金额上限" prop="cashbackLimitPerson">
          <a-space>
            <a-input-number placeholder="请输入单个收银员返现金额上限" v-model="beanInfo.cashbackLimitPerson" :min="0" :disabled="disabled"/>
            <span>元</span>
          </a-space>
        </form-item>
        <div class="hr" v-if="current === 2"></div>
        <form-item label="单个收银员返现退出条件" :wrapper-col="{span:12}">
          <div style="line-height: 1.4;margin-top: 10px">
            以下整体返现活动退出条件,<br>不配置则活动结束自然退出(可能需要补营销资金),<br><span style="color: #F1545D;">满足其中之一则所有收银员不再享受返现优惠！</span>
          </div>
        </form-item>
        <form-item label="纳入返现总交易笔数上限" prop="quantityLimitMc">
          <a-space>
            <a-input-number placeholder="请输入纳入返现总交易笔数上限" v-model="beanInfo.quantityLimitMc" :min="0" :precision="0" :disabled="disabled"/>
            <span>笔，或</span>
          </a-space>
        </form-item>
        <form-item label="纳入返现总交易金额上限" prop="amountLimitMc">
          <a-space>
            <a-input-number placeholder="请输入纳入返现总交易金额上限" v-model="beanInfo.amountLimitMc" :min="0" :disabled="disabled"/>
            <span>元，或</span>
          </a-space>
        </form-item>
        <form-item label="返现总金额上限" prop="cashbackLimitMc">
          <a-space>
            <a-input-number placeholder="请输入返现总金额上限" v-model="beanInfo.cashbackLimitMc" :min="0" :disabled="disabled"/>
            <span>元</span>
          </a-space>
        </form-item>
        <form-item label="付款账户" prop="payAcctNo" v-model="beanInfo.payAcctNo" input-type="select" v-if="operatorType === 'release' &&  beanInfo.skipPub !== '1' || (beanInfo.payAcctNo && current === 2)" :options="paymentAccounts" :disabled="operatorType !== 'release'"></form-item>
        <form-item label="审核意见" prop="auditRefuseReason" v-model="beanInfo.auditRefuseReason" input-type="textarea" v-if="operatorType === 'examine' || (beanInfo.auditRefuseReason && current === 2)" :disabled="operatorType !== 'examine'"></form-item>
        <form-item label="发布意见" prop="publishRefuseReason" v-model="beanInfo.publishRefuseReason" input-type="textarea" v-if="operatorType === 'release' || (beanInfo.publishRefuseReason && current === 2)" :disabled="operatorType !== 'release'"></form-item>
      </entity-view>
    </template>
    <template v-slot:footer>
      <a-space>
        <a-button type="primary" v-if="current < 2" @click="next">下一步</a-button>
        <a-button type="primary" v-if="current === 2 && (operatorType === 'add' || operatorType === 'edit')" @click="submit">确认创建</a-button>
        <a-button type="primary" v-if="current === 2 && (operatorType === 'add' || operatorType === 'edit')" @click="save(false)">保存草稿</a-button>
        <a-button type="primary" v-if="current === 2 && operatorType === 'examine'" @click="examine(true)">审核通过</a-button>
        <a-button type="primary" v-if="current === 2 && operatorType === 'examine'" @click="examine(false)">审核退回</a-button>
        <a-button type="primary" v-if="current === 2 && operatorType === 'release' && beanInfo.skipPub !== '1'" @click="release(true)">打款，发布</a-button>
        <a-button type="primary" v-if="current === 2 && operatorType === 'release' && beanInfo.skipPub === '1'" @click="release(true)">发布</a-button>
        <a-button type="primary" v-if="current === 2 && operatorType === 'release'" @click="release(false)">退回修改</a-button>
        <a-button type="primary" v-if="current > 0 && (operatorType === 'add' || operatorType === 'edit')" @click="back">返回</a-button>
        <a-button type="primary" @click="visible = false">关闭</a-button>
      </a-space>
    </template>
  </a-modal>
</template>

<script>
import FormItem from "../../../../../components/common/entityView/FormItem";
import EntityView from "../../../../../components/common/entityView/EntityView";
import MerchantSelector from '@/views/bizimpl/upmp/market/cashierManager/MerchantSelector'
import { TreeSelect } from 'ant-design-vue';
const SHOW_PARENT = TreeSelect.SHOW_PARENT;
import moment from 'moment'

let loadingLock = false
let pIdCache = []
// getChildNodes和 getParentNodes 有可能影响性能，有待优化。
const getChildNodes = (nodes, treeObj) => {
  let childNodes = []
  nodes.forEach(node => {
    if (typeof node === 'string') {
      node = treeObj[node]
    }
    if (node && !pIdCache.includes(node.pId)) {
      const filterNodes = Object.values(treeObj).filter(i => i.pId === node.id)
      if (filterNodes.length) {
        childNodes.push(...filterNodes)
        pIdCache.push(node.id)
        childNodes.push(...getChildNodes(filterNodes, treeObj))
      }
    }
  })
  return childNodes
}
const getParentNodes = (nodes, treeObj) => {
  let parentNodes = []
  nodes.forEach(node => {
    if (typeof node === 'string') {
      node = treeObj[node]
    }
    if (node && node.pId && node.pId !== '999999999' && pIdCache.includes(node.pId) === false) {
      pIdCache.push(node.pId)
      const filterNodes = Object.values(treeObj).filter(i => i.id === node.pId)
      if (filterNodes.length) {
        parentNodes.push(...filterNodes)
        parentNodes.push(...getParentNodes(parentNodes, treeObj))
      }
    }
  })
  return parentNodes
}

const beanInfoInitData = {
  mcNo: "", // 营销活动编号
  mcName: "", // 营销活动名称
  orgInfo: [], // 参与机构
  checkedOrgInfo: [], // 已选中的参与机构
  mcDateRange: [], // 活动起始时间
  discountTransferMode: "0", // 活动优惠方式
  budget: null, // 返现金额  数字格式 隐式转换
  merchantInfo: [], // 商户信息
  merchantCircleInfo: [], // 商圈信息
  upLineProduce: [], // 纳入营销的交易
  criteriaLimit: null, // 有效交易定义
  statPeriod: "", // 统计周期
  criteriaAmount: null, // 周期内收银员交易金额达标
  criteriaFlag: "0", // 周期内收银员交易金额达标条件计算方式
  criteriaQuantity: null, // 周期内收银员交易笔数达标
  cashbackMethod: "0", // 营销方式交易类型
  ruleInfo: [{
    discountType: "0", // 优惠类型
  }], // 营销方式阶梯规则
  quantityLimitPerson: "", // 单个收银员统计交易笔数上限
  amountLimitPerson: "", // 单个收银员统计交易金额上限
  cashbackLimitPerson: "", // 单个收银员返现金额上限
  quantityLimitMc: "", // 纳入返现总交易笔数上限
  amountLimitMc: "", // 纳入返现总交易金额上限
  cashbackLimitMc: "", // 返现总金额上限
  hasUploaded: false,
  mrctFilePath: '',
}

export default {
  name: "CashierManagerOperation",
  components: {EntityView, FormItem, MerchantSelector},
  data () {
    const mcDataRangeValidator = (rule, val, cb) => {
      if (!val || val.length === 0) {
        cb(new Error('请选择时间范围'));
      } else {
        cb();
      }
    }
    const ruleInfoValidator = (rule, val, cb) => {
      for (let i = 0; i < val.length; i++) {
        const item = val[i];
        if (this.beanInfo.cashbackMethod === '0') {
          if (!(
            item.criteriaFloor !== undefined && item.criteriaFloor !== null &&
            item.criteriaCelling !== undefined && item.criteriaCelling !== null &&
            item.cashbackRatio !== undefined && item.cashbackRatio !== null &&
            item.discountType !== undefined && item.discountType !== null &&
            item.discount !== undefined && item.discount !== null
          )) {
            cb(new Error(`请完善第${i + 1}行营销方式阶梯`));
            return
          }
          if (item.cashbackRatio <= 0) {
            cb(new Error(`第${i + 1}行营销方式阶梯的返现比例数值不能为零并且不能大于1000`));
            return
          }
        } else if (this.beanInfo.cashbackMethod === '1') {
          if (!(
            item.criteriaFloor !== undefined && item.criteriaFloor !== null &&
            item.criteriaCelling !== undefined && item.criteriaCelling !== null &&
            item.discountType !== undefined && item.discountType !== null &&
            item.discount !== undefined && item.discount !== null
          )) {
            cb(new Error(`请完善第${i + 1}行营销方式阶梯`));
            return
          }
        }
        if (Number(item.criteriaFloor) > Number(item.criteriaCelling)) {
          cb(new Error(`第${i + 1}行营销方式阶梯的交易金额区间的结束值必须大于区间的开始值`));
          return
        }
      }
      cb();
    }
    const payAcctNoValidator = (rule, val, cb) => {
      if (this.operatorType === 'release') {
        if (!this.beanInfo.payAcctNo && this.beanInfo.skipPub !== '1') {
          cb(new Error(`请选择支付账号`));
        } else {
          cb();
        }
      } else {
        cb()
      }
    }
    const merchantInfoValidator = (rule, val, cb) => {
      if (!this.beanInfo.merchantInfo.length && !this.beanInfo.merchantCircleInfo.length && !this.beanInfo.hasUploaded) {
        cb(new Error(`请输入商户或商圈信息，或者使用导入功能`));
      } else {
        cb()
      }
    }
    return {
      SHOW_PARENT,
      firstStepRules: {
        mcName: [{required: true, message: "请输入收银员返现活动名称", trigger: "blur"}],
        orgInfo: [{required: true, trigger: "change", message: "请选择参与机构"}],
        mcDateRange: [{required: true, trigger: "change", validator: mcDataRangeValidator,}],
        budget: [
          {required: true, message: "请输入预计活动资金", trigger: "blur"},
          {type: "number", message: "请输入数字", trigger: "blur"},
          {
            trigger: 'blur',
            validator: (rule, val, cb) => val <= 0 ? cb(new Error(`预计活动返现资金必须大于0`)) : cb()
          },
        ],
        upLineProduce: [{required: true, message: "请勾选需要纳入营销的交易方式", trigger: "change"}],
        merchantInfo: [{required: true, trigger: "change", validator: merchantInfoValidator}],
      },
      secondStepRules: {
        criteriaLimit: [{required: true, message: "请输入有效交易金额", trigger: "blur"}, {type: "number", message: "请输入数字", trigger: "blur"}],
        statPeriod: [{required: true, message: "请选择统计周期", trigger: "change"}],
        criteriaAmount: [{required: true, message: "请输入周期内收银员交易达标金额", trigger: "blur"}, {type: "number", message: "请输入数字", trigger: "blur"}],
        criteriaQuantity: [{required: true, message: "请输入周期内收银员交易达标笔数", trigger: "blur"}, {type: "number", message: "请输入数字", trigger: "blur"}],
        ruleInfo: [{required: true, trigger: "blur", validator: ruleInfoValidator,}],
        payAcctNo: [{required: true, trigger: "blur", validator: payAcctNoValidator,}],
      },
      operatorType: 'add',
      beanInfo: Object.assign({}, beanInfoInitData),
      visible: false,
      current: 0, // 当前步骤
      indeterminate: false,
      checkAll: false,
      treeData: [],
      upLineProduceList: [
        'PM003000',
        'PM003010',
        'PM003020',
        'PM003030',
        'MC021000',
        'MC021010',
        'MC021020',
      ],
      paymentAccounts: [], // 支付账户列表
      checkedOrgInfo: [],
    }
  },
  computed: {
    calcTitle() {
      let title = '收银员营销活动';
      switch (this.operatorType) {
        case 'edit':
          title = '编辑' + title;
          break;
        case 'view':
          title = '查看' + title;
          break;
        case 'add':
          title = '新增' + title;
          break;
        case 'examine':
          title = '审核' + title;
          break;
        case 'release':
          title = '发布' + title;
          break;
      }
      return title
    },
    treeObj () {
      return this.treeData.reduce((i, next) => {
        i[next.id] = next
        return i
      }, {})
    },
    disabled() {
      return this.current === 2
    },
  },
  methods: {
    async initTreeData() {
      try {
        const res = await this.$get('/admin/market/cashierManager/getOrgList');
        this.treeData = (res.data || []).map(i => {
          i.id = i.orgCode
          i.orgId = i.orgCode
          i.value = i.orgCode
          i.label = i.orgName
          i.pId = i.superOrgCode
          return i
        });
        if (this.operatorType === 'edit' && this.visible) {
          this.setOrgInfo()
        }
      } catch (e) {
        this.$message.error('获取机构树失败');
      }
    },
    setBeanInfo(beanInfo) {
      this.checkAll = beanInfo.upLineProduce.length === this.upLineProduceList.length
      if (beanInfo.orgInfo.length) {
        const orgInfo = beanInfo.orgInfo.map(i => {
          return this.treeObj[i]
        })
        orgInfo.forEach(i => {
          if (i !== null && i !== undefined) {
            const index = beanInfo.orgInfo.indexOf(i.superOrgCode)
            if (index > -1) {
              beanInfo.orgInfo.splice(index, 1)
            }
          }
        })
      }
    },
    show (beanInfo, operatorType) {
      this.operatorType = operatorType;
      this.visible = true;
      switch (operatorType) {
        case 'add':
          this.current = 0
          this.$nextTick(() => {
            this.$refs.firstStepForm.resetFields()
            this.checkAll = true
            this.beanInfo = Object.assign({}, beanInfoInitData)
            this.beanInfo.upLineProduce = this.upLineProduceList
          })
          break;
        case 'edit':
          this.current = 0
          this.$nextTick(() => {
            this.$refs.firstStepForm.resetFields()
            this.setBeanInfo(beanInfo)
            this.beanInfo = Object.assign({}, beanInfo)
            this.setOrgInfo()
          })
          break;
        case 'view':
        case 'examine':
          this.current = 2
          this.setBeanInfo(beanInfo)
          this.beanInfo = beanInfo
          break
        case 'release':
          this.current = 2
          this.setBeanInfo(beanInfo)
          this.beanInfo = beanInfo
          this.getPaymentAccounts()
          break
        default:
          this.$message.error('操作类型错误');
      }
    },
    hide () {
      this.visible = false;
      this.beanInfo = {};
    },
    setLongTime(){
      this.$set(this.beanInfo, 'mcDateRange', [moment().format('YYYY-MM-DD'), moment(new Date('2099/12/31')).format('YYYY-MM-DD')])
    },
    async getBusinessArea () {
      if (this.beanInfo.orgInfo.length === 0) {
        this.$message.error('请先选择参与机构');
        return
      }
      if (!this.beanInfo.merchantCircleRows || !this.beanInfo.merchantCircleRows.trim()) {
        this.$message.error('请输入商圈！');
        return
      }
      let merchantCircleList = this.beanInfo.merchantCircleRows.split('\n').filter(i => i.trim())
      if (merchantCircleList.length > 10) {
        this.$message.error('最多输入10个商户号！');
        return
      }
      // 去重
      merchantCircleList = [...new Set(merchantCircleList)]
      // 与之前输入的商户号对比去重
      let oldMerchantCircleList = this.beanInfo.merchantCircleInfo.map(i => i.mchntNo)
      // 因为商圈支持模糊搜索所以去重放到请求完毕做
      // merchantCircleList = merchantCircleList.filter(i => !oldMerchantCircleList.includes(i))
      // if (merchantCircleList.length === 0) {
      //   this.$set(this.beanInfo, 'merchantCircleRows', '')
      //   this.$message.error('请输入新的商圈！');
      //   return
      // }
      const hide = this.$message.loading('正在查询商圈信息...', 0);
      try {
        const res = await this.$postJson('/admin/market/cashierManager/getMcCircletList', {
          data: merchantCircleList.join(','),
          selectedOrgInfoList: this.checkedOrgInfo
        })
        if (res.data.code === '100000') {
          let successData = res.data.data.successData
          // 特殊费率的商户也可以添加
          const feeMchntObj = res.data.data.feeMchntData;
          successData = successData.concat(feeMchntObj);

          const errorData = res.data.data.errorData
          if (errorData.length > 0) {
            this.$notification.error({
              message: '提示',
              description: `录入的商圈/商户编号：${errorData.map(i => i.mchntNo).join(',')}存在错误，请重新输入！`,
              duration: 0
            });
          }
          const orgMchntData = res.data.data.orgMchntData;
          if (orgMchntData.length > 0) {
            this.$notification.error({
              message: '提示',
              description: `输入的商户或商圈内的商户所属的机构与已选的机构不符,${orgMchntData.map(i => i.mchntNo).join(',')}不符合要求，请重新输入！`,
              duration: 0
            });
          }
          if (successData.length) {
            successData = successData.filter(i => !oldMerchantCircleList.includes(i.mchntNo))
            if (!successData.length) {
              this.$message.error('输入重复，请输入新的商圈！');
            } else {
              this.$set(this.beanInfo, 'merchantCircleInfo', this.beanInfo.merchantCircleInfo.concat(successData))
            }
          }
          this.$set(this.beanInfo, 'merchantCircleRows', '')
        } else {
          this.$message.error(res.data.message);
        }
      } catch (e) {
        this.$message.error('获取商户失败');
        console.error(e)
      }
      hide()
    },
    onCheckAllChange (e) {
      Object.assign(this, {
        indeterminate: false,
        checkAll: e.target.checked,
      });
      this.$set(this.beanInfo, 'upLineProduce', e.target.checked ? this.upLineProduceList : []);
      this.$refs.upLineProduce.onFieldChange()
    },
    onCheckboxChange () {
      this.indeterminate = !!this.beanInfo.upLineProduce.length && this.beanInfo.upLineProduce.length < this.upLineProduceList.length;
      this.checkAll = this.beanInfo.upLineProduce.length === this.upLineProduceList.length;
      this.$refs.upLineProduce.onFieldChange()
    },
    async next () {
      if (this.current === 0) {
        try {
          await this.$refs.firstStepForm.validate();
          this.current++
        } catch (e) {
          console.log(e);
        }
      } else if (this.current === 1) {
        try {
          await this.$refs.secondStepForm.validate();
          this.current++
          if (this.operatorType === 'add') {
            this.$nextTick(() => {
              this.$refs.secondStepForm.resetFields()
            })
          }
        } catch (e) {
          console.log(e);
        }
      }
    },
    async examine (isExamine) {
      if (loadingLock) {
        this.$message.error('保存中，请勿重复点击');
        return
      }
      if (!isExamine && !this.beanInfo.auditRefuseReason) {
        this.$message.error('请填写审核不通过原因');
        return
      }
      loadingLock = true
      let hideLoading
      try{
        await this.$refs.secondStepForm.validate();
        !this.beanInfo.auditRefuseReason && (this.beanInfo.auditRefuseReason = '')
        const params = {
          mcNo: this.beanInfo.mcNo,
          oprContent: this.beanInfo.auditRefuseReason.trim(),
          oprType: isExamine ? '1' : '2'
        }
        hideLoading = this.$message.loading('提交中...', 0)
        const res = await this.$postJson(`/admin/market/cashierManager/checkCash?mcNo=${params.mcNo}&oprContent=${params.oprContent}&oprType=${params.oprType}`)
        if (res.data.code === '100000') {
          this.$message.success(`${isExamine ? '审核' : '退回'}成功`)
          this.visible = false
          this.$emit('refresh')
        } else {
          this.$message.error(res.data.message);
        }
      } catch (e) {
        console.log(e)
        if (e !== false) {
          this.$message.error('审核出错');
        }
      }
      hideLoading && hideLoading()
      loadingLock = false
    },
    async release (isRelease) {
      if (loadingLock) {
        this.$message.error('保存中，请勿重复点击');
        return
      }
      if (!isRelease && !this.beanInfo.publishRefuseReason) {
        this.$message.error('请填写发布拒绝原因');
        return
      }
      !this.beanInfo.publishRefuseReason && (this.beanInfo.publishRefuseReason = '')

      let hideLoading
      try {
        await this.$refs.secondStepForm.validate()
        let currentPaymentAccount = this.paymentAccounts.filter(i => i.payAcctNo === this.beanInfo.payAcctNo)[0]
        if(this.beanInfo.skipPub !== '1') {
          if (!currentPaymentAccount) {
            this.$message.error('获取支付信息出错，请重试')
            return
          }
        } else {
          !currentPaymentAccount && (currentPaymentAccount = {})
        }
        const params = {
          mcNo: this.beanInfo.mcNo,
          oprType: isRelease? '0': '1',
          payAcctNo: this.beanInfo.payAcctNo,
          oprContent: this.beanInfo.publishRefuseReason.trim(),
          idType: currentPaymentAccount.idType,
          idNo: currentPaymentAccount.idNo,
          cellPhoneNumber: currentPaymentAccount.cellPhoneNumber,
          picCapcha: currentPaymentAccount.picCapcha,
          smsCapcha: currentPaymentAccount.smsCapcha,
        }
        const confirmResult = await new Promise((resolve, reject) => {
          this.$confirm({
            title: '提示',
            content: `请确认打款账号：${params.payAcctNo}`,
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
              resolve(true)
            },
            onCancel: () => {
              resolve(false)
            }
          })
        })
        if (!confirmResult){
          return
        }
        loadingLock = true
        hideLoading = this.$message.loading('提交中...', 0)
        const res = await this.$postJson(`/admin/market/cashierManager/releaseAgent?mcNo=${params.mcNo}&oprType=${params.oprType}&payAcctNo=${params.payAcctNo}&oprContent=${params.oprContent}&idType=${params.idType}&idNo=${params.idNo}&cellPhoneNumber=${params.cellPhoneNumber}&picCapcha=${params.picCapcha}&smsCapcha=${params.smsCapcha}`)
        if (res.data.code === '100000') {
          this.$message.success('发布成功')
          this.visible = false
          this.$emit('refresh')
        } else {
          this.$message.error(res.data.message);
        }
        hideLoading()
      } catch (e) {
        console.error(e)
      }
      hideLoading && hideLoading()
      loadingLock = false
    },
    submit() {
      this.save(true)
    },
    async save (isSubmit) {
      if (loadingLock) {
        this.$message.error('保存中，请勿重复点击');
        return
      }
      loadingLock = true
      const params = JSON.parse(JSON.stringify(this.beanInfo))
      params.merchantInfo = []
      if (params.mcDateRange.length === 2) {
        params.mcStartDate = params.mcDateRange[0].substring(0, 10)
        params.mcEndDate = params.mcDateRange[1].substring(0, 10)
      }
      if (params.ruleInfo) {
        params.ruleInfo.forEach((i, index) => {
          i.ruleIndex = index + 1
        })
      }
      if (params.orgInfo) {
        params.orgInfo = this.checkedOrgInfo
        // params.orgInfo = JSON.stringify(params.orgInfo)
      }
      const hide = this.$message.loading("保存中...",0);
      if (this.operatorType === 'edit') { // 如果是编辑状态则把标记删除的商户或商圈删除
        const res = await this.getDeleteMerchants()
        if (!res) {
          loadingLock = false
          hide()
          this.$message.error("保存失败")
          return
        } else {
          params.merchantInfo.push(...res)
        }
      }
      if (this.beanInfo.merchantInfo && this.beanInfo.merchantInfo.length) {
        params.merchantInfo.push(...this.beanInfo.merchantInfo.map(i => {
          i.oprType = i.oprType || 'I'
          i.mchntType = '0'
          return i
        }))
      }

      if (params.merchantCircleInfo) {
        params.merchantCircleInfo = this.beanInfo.merchantCircleInfo.map(i => {
          i.oprType = i.oprType || 'I'
          i.mchntType = '1'
          return i
        })
      }
      if (params.quantityLimitPerson || params.amountLimitPerson || params.cashbackLimitPerson) {
        params.terminationFlagPerson = '1'
      } else {
        params.terminationFlagPerson = '0'
      }
      if (params.quantityLimitMc || params.amountLimitMc || params.cashbackLimitMc) {
        params.terminationFlagMc = '1'
      } else {
        params.terminationFlagMc = '0'
      }
      try {
        if (isSubmit) {
          params.auditStatus = '01'
        }
        const url = isSubmit ? '/admin/market/cashierManager/createCampaign' : '/admin/market/cashierManager/saveCampaign'
        const res = await this.$postJson(url, params)
        if (res.data.code === '100000') {
          this.$message.success('保存成功');
          if (isSubmit) {
            this.visible = false
            this.$emit('refresh')
          }
        } else {
          this.$message.error("保存失败");
        }
      } catch (e) {
        console.error(e)
      }
      hide();
      loadingLock = false
    },
    back () {
      this.current--
    },
    addStepRuleItem() {
      const ruleInfo = this.beanInfo.ruleInfo;
      const lastRule = ruleInfo[ruleInfo.length - 1];
      this.$refs.secondStepForm.validateField('ruleInfo', (errorMessage) => {
        if (!errorMessage) {
          ruleInfo.push({
            criteriaFloor: lastRule.criteriaCelling,
            criteriaCelling: null,
            cashbackRatio: null,
            discountType: '0',
            discount: null,
          })
          this.$set(this.beanInfo, 'ruleInfo', ruleInfo);
        }
      })
    },
    deleteMerchantInfo (key, index) {
      this.$confirm({
        title: '提示',
        content: '确定删除该商户？',
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          this.beanInfo[key].splice(index, 1)
          this.$set(this.beanInfo, key, this.beanInfo[key])
        }
      })
    },
    onCashbackChange () {
      this.$set(this.beanInfo, 'ruleInfo', [{
        discountType: '0'
      }])
    },
    deleteCashbackRule (index) {
      const ruleInfo = this.beanInfo.ruleInfo
      ruleInfo.splice(index, 1)
      this.$set(this.beanInfo, 'ruleInfo', ruleInfo)
    },

    setOrgInfo () {
      if (Object.keys(this.treeObj).length) {
        // get child node
        let checkedNodes = this.beanInfo.orgInfo.map(i => this.treeObj[i]).filter(i => !!i)
        pIdCache = []
        checkedNodes = checkedNodes.concat(getChildNodes(this.beanInfo.orgInfo, this.treeObj))
        pIdCache = []
        checkedNodes = checkedNodes.concat(getParentNodes(this.beanInfo.orgInfo, this.treeObj))
        checkedNodes = Object.values(checkedNodes.reduce((item, next) => {
          item[next.id] = next
          return item
        }, {}))
        this.checkedOrgInfo = checkedNodes
      }
    },
    merchantListChange (needToDelete) {
      if (needToDelete && this.operatorType === 'edit') {
        this.beanInfo.deleteMerchants = needToDelete
      }
    },
    async getDeleteMerchants () {
      if (!this.beanInfo.deleteMerchants || this.beanInfo.deleteMerchants.length === 0) {
        return []
      }
      const params = {
        mchntType: '0',
        selectedOrgInfoList: this.checkedOrgInfo,
        mchntNo: this.beanInfo.deleteMerchants,
      }
      try {
        const res = await this.$postJson("/admin/market/commissionManager/getMerchanList", params)
        if (res.data.type === 'failure') {
          this.$message.error(res.data.message)
        } else {
          const merchantInfo = [];
          const successData = res.data.data.successData || [];
          const feeMchntData = res.data.data.feeMchntData || [];
          const orgMchntData = res.data.data.orgMchntData || [];
          if (successData.length) {
            merchantInfo.push(...successData.map(i => {
              i.oprType = 'D'
              i.mchntType = '0'
              return i
            }))
          }
          if (feeMchntData.length) {
            merchantInfo.push(...feeMchntData.map(i => {
              i.oprType = 'D'
              i.mchntType = '0'
              return i
            }))
          }
          if (orgMchntData.length) {
            merchantInfo.push(...orgMchntData.map(i => {
              i.oprType = 'D'
              i.mchntType = '0'
              return i
            }))
          }
          return merchantInfo
        }
      } catch (e) {
        console.error(e)
        this.$message.error("获取删除商户信息失败")
      }
    },
    async getPaymentAccounts () {
      if (this.paymentAccounts.length) {
        return
      }
      try {
        const res = await this.$get('admin/market/cashierManager/getMcAccountInfo')
        if (res.data.code === '100000') {
          this.paymentAccounts = res.data.data.result.acctInfoObk.map(i => {
            i.name = i.payAcctNo
            i.value = i.payAcctNo
            return i
          })
        } else {
          this.$message.error(res.data.message)
        }
      } catch (e) {
        this.$message.error("获取支付账户信息出错")
        console.error(e)
      }
    },
    async downloadTemplate () {
      try {
        await this.$download('admin/market/cashierManager/getExcel?type=0',{}, 'mchntNoBatchImportTemplate.xls')
      } catch (e) {
        console.error(e)
      }
    },
    async importTemplate () {
      const formData = new FormData()
      const orgInfo = this.checkedOrgInfo
      if (orgInfo.length === 0) {
        this.$message.error('请选择参与机构')
        return
      }
      const fileInput = document.createElement('input')
      fileInput.type = 'file'
      fileInput.accept = '.xls,.xlsx'
      fileInput.onchange = async () => {
        const file = fileInput.files[0]
        if (!file) {
          this.$message.error('请选择文件')
          return
        }
        formData.append('excelFile', file)
        try {
          const res = await this.$upload('admin/market/cashierManager/upload', formData)
          if (res.data.code === '100000') {
            this.$message.success('导入成功')
            this.$set(this.beanInfo, 'hasUploaded', true)
            this.$set(this.beanInfo, 'mrctFilePath', res.data.data)
          } else {
            this.$message.error(res.data.message)
          }
        } catch (e) {
          console.error(e)
          this.$message.error('导入失败')
        }
      }
      fileInput.click()
    },
    templateUploaded (fileUrl) {
      this.$set(this.beanInfo, 'hasUploaded', true)
      this.$set(this.beanInfo, 'mrctFilePath', fileUrl)
    },
    disabledDate ({current, minDate, maxDate}) {
      minDate = minDate || moment().subtract(1, 'day')
      if (maxDate) {
        return maxDate.isSameOrBefore(current, 'day') || current.isSameOrBefore(minDate, 'day')
      } else {
        return current && current.isSameOrBefore(minDate, 'day')
      }
    }
  },
  mounted () {
    this.initTreeData();
  }
}
</script>

<style scoped>
.child-item{
  background: #F7F8FA;
  border: 1px solid #E0E0E0;
  padding: 20px;
  border-radius: 2px;
  margin: 20px 0;
}
.tip{
  line-height: 1.4;
}
.label {
  margin: 20px 0 10px;
}
.step-rule-item {
  display: flex;
  line-height: 1.8;
}
.small-input {
  width: 70px;
  margin: 0 5px;
}
.small-select {
  width: 100px;
  margin: 0 5px;
}
.hr {
  width: 100%;
  height: 1px;
  background: #E0E0E0;
  margin: 10px 0;
}
.form-item {
  width: 50%;
  padding-left: 10px;
  padding-right: 10px;
}
</style>
